package com.shujia.io.seven;

import org.junit.Test;

import java.io.*;

public class RandomRWSteamTest {


    @Test
    public void test1() {

        insertContent("file\\a.txt", "花钿委地无人收", 24);
    }

    public void insertContent(String fileName, String content, long point) {
        try (RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
             OutputStream os = new FileOutputStream("file\\temp");
             InputStream is = new FileInputStream("file\\temp")) {
            // 把指针后面的内容写入到临时文件, 因为直接写的话会覆盖后面的内容
            raf.seek(point);

            byte[] bys = new byte[1024];
            int len;

            while ((len = raf.read(bys)) != -1) {
                os.write(bys, 0, len);
            }

            // 插入文本信息
            System.out.println(raf.getFilePointer());// 文件末尾

            raf.seek(point);
            raf.write(content.getBytes());

            // 追加记录的临时文件
            while ((len = is.read(bys)) != -1) {
                raf.write(bys, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
